#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
Модуль для поиска троественных парагенезисов среди множества плоскостей.
Тройственным парагенезисом считается тройка плоскостей, у которых двугранный
угол между друг другом равен 90 +/- 20.
"""

import sys, os
from optparse import OptionParser

import fr_parser
from plane import Plane

# Parsing of an options
optparser= OptionParser()
optparser.add_option('-o', '--output-prefics', dest='output',
                     help='Prefics for output files of triples')
optparser.add_option('-v', '--verbose',  dest='verbose',
                     help='Verbose mode.',
                     action='store_true',
                     default=False)                     
options, args = optparser.parse_args(sys.argv[1:])

# Parsig of a maximums
lines = sys.stdin.read().split('\n')
maxs = []
for line in lines:
    val = fr_parser.parse_line(line)
    if val: maxs.append(val)    

triples = []
while len(maxs) != 0:
    pl1 = maxs.pop(0)
    plane1 = Plane(pl1[0], pl1[1])
    index_list = range(len(maxs)) # small trick to prevent duplicates in result
    while len(index_list) != 0:
        index = index_list.pop(0)
        plane2 = Plane(maxs[index][0], maxs[index][1])
        angle_12 = plane1.normal().return_angle_between(plane2.normal())
        if abs(angle_12 - 90) > 30: continue
        for index in index_list:
            plane3 = Plane(maxs[index][0], maxs[index][1])
            if plane3.dir == plane2.dir and plane3.dip == plane2.dip: continue
            angle_13 = plane1.normal().return_angle_between(plane3.normal())
            angle_23 = plane2.normal().return_angle_between(plane3.normal())
            if abs(angle_13 - 90) > 30 or abs(angle_23 - 90) > 30: continue
            triples.append([plane1, plane2, plane3])

os.system("rm -f %s.*" % options.output)
for i, triple in enumerate(triples): 
    plane1, plane2, plane3 = triple[0], triple[1], triple[2]
    angle_12 = plane1.normal().return_angle_between(plane2.normal())
    angle_13 = plane1.normal().return_angle_between(plane3.normal())
    angle_23 = plane2.normal().return_angle_between(plane3.normal())
    output_name = "%s.%s" % (options.output, i)
    f = open(output_name, 'w')
    f.write("# plane1-plane2 anlge: %003d\n" % angle_12)
    f.write("# plane1-plane3 anlge: %003d\n" % angle_13)
    f.write("# plane2-plane3 anlge: %003d\n" % angle_23)
    f.write("%003d %02d # plane1\n" % (plane1.dir, plane1.dip))
    f.write("%003d %02d # plane2\n" % (plane2.dir, plane2.dip))
    f.write("%003d %02d # plane3\n" % (plane3.dir, plane3.dip))
    f.close()

    if options.verbose:
        print "%02d | %003d %02d   %003d %02d   %003d %02d | %003d %003d %003d" % \
                 (i, plane1.dir, plane1.dip, plane2.dir, plane2.dip, 
                  plane3.dir, plane3.dip, angle_12, angle_13, angle_23)
        

